package com.yuwenchao.superafflatus.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ObjectListing;
import com.yuwenchao.superafflatus.constant.AfflatusConstant;
import com.yuwenchao.superafflatus.mapper.SuperLoginUserMapper;
import com.yuwenchao.superafflatus.pojo.entity.SuperLoginUser;
import com.yuwenchao.superafflatus.pojo.entity.SuperMusic;
import com.yuwenchao.superafflatus.service.SuperMusicService;
import com.yuwenchao.superafflatus.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author chaooGG
 * @version 1.0
 * @date 2021/6/3 17:26
 */
@Slf4j
@Api(tags = "系统常用功能")
@Controller
//@RequestMapping("admin")
public class FunctionSystemController {


    @Value("${spring.tencent.cos.base-url}")
    private String baseUrl;


    SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd");

    @Autowired
    Producer producer;


    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    SuperLoginUserMapper superLoginUserMapper;

    @Autowired
    SuperMusicService superMusicService;

    @Autowired
    TxOssUpdateController txOssUpdateController;


    //这个代码打包后会出现问题
    @ApiOperation(value = "初始化菜单")
    @GetMapping("init")
    @ResponseBody
    public JSONObject getinit() {


        String jsonStr = "";
        try {
            File jsonFile = ResourceUtils.getFile(AfflatusConstant.INIT);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
         //   InputStream input = new ClassPathResource(AfflatusConstant.INIT).getInputStream();

            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            JSONObject jsonObj = new JSONObject(jsonStr);


           // log.info("json对象数据："+jsonObj);
            return jsonObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //打包后运行
    @ApiOperation(value = "初始化菜单")
    @GetMapping("initNew")
    @ResponseBody
    public JSONObject getNewinit() {

        Object jsonObj1 = redisTemplate.opsForValue().get("jsonObj");
        if (jsonObj1==null){
            String jsonStr = "";
            try {
           /* File jsonFile = ResourceUtils.getFile(AfflatusConstant.INIT);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");*/

                InputStream input = new ClassPathResource(AfflatusConstant.NEW_INIT).getInputStream();
                Reader reader1 = new InputStreamReader(input,"utf-8");


                int ch = 0;
                StringBuffer sb = new StringBuffer();
                while ((ch = reader1.read()) != -1) {
                    sb.append((char) ch);
                }
                //fileReader.close();
                reader1.close();
                jsonStr = sb.toString();
                JSONObject jsonObj = new JSONObject(jsonStr);

                redisTemplate.opsForValue().set("jsonObj",jsonObj);
                // log.info("json对象数据："+jsonObj);
                return jsonObj;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        JSONObject jsonObj = new JSONObject(jsonObj1);
       log.info("菜单页缓存中有内容!");
        log.info(""+jsonObj);
        return jsonObj;

    }


    @ApiOperation(value = "清理菜单页面缓存")
    @GetMapping("clearMenu")
    @ResponseBody
    public void clearMenu() {
       // String menu = (String) redisTemplate.opsForValue().get("/jsonObj");
        Boolean jsonObj = redisTemplate.delete("jsonObj");
        if(jsonObj){
            log.info("清理菜单缓存成功!");
           // return R.ok().message("清理菜单缓存成功!");
        }else{
            log.info("清理菜单缓存失败!");
           // return R.error().message("清理菜单缓存失败!");
        }
    }


    @ApiOperation(value = "清理redis所有缓存")
    @GetMapping("clearWeb")
    @ResponseBody
    public void clearWeb() {
        Set<Object> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        log.info("清理redis所有缓存成功!");
    }


    @ApiOperation(value = "打开计算器")
    @GetMapping("opencalc")
    @ResponseBody
    public void opencalc() {
        //打开计算器
        RuntimeUtil.exec("calc");
    }

    @ApiOperation(value = "打开画图")
    @GetMapping("openmspaint")
    @ResponseBody
    public void openmspaint() {
        //打开画图
        RuntimeUtil.exec("mspaint");

    }

    @ApiOperation(value = "金额转换大写")
    @GetMapping("amountInWords")
    @ResponseBody
    public String amountInWords(@RequestParam(value = "amount",required = true) Double amount) {
        String amountInWords = Convert.digitToChinese(amount);
        System.out.println("转换后的金额:" + amountInWords);
        return amountInWords;
    }




    @ApiOperation("验证码输出")
    @GetMapping("/verify-code")
    @ResponseBody
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpg");
        String text = producer.createText();
        session.setAttribute("verifyCode", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream out = resp.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }
    }



    @ApiOperation(value = "获取登录用户信息")
    public  SuperLoginUser getSuperLoginUserInfo() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("获取到的用户信息"+username);
        QueryWrapper<SuperLoginUser> loginUserQueryWrapper = new QueryWrapper<>();
        loginUserQueryWrapper.eq("username",username);
        SuperLoginUser superLoginUser = superLoginUserMapper.selectOne(loginUserQueryWrapper);
        return superLoginUser;
    }


    /**
     * 获取Ip地址
     * @param request
     * @return
     */
    @ApiOperation("获取ip地址")
    @GetMapping("/getIp")
    @ResponseBody
    private static String getIpAddress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }


    @ApiOperation(value = "初始化music表数据")
    @GetMapping("initMusic")
    @ResponseBody
    public R initMusic() {
        superMusicService.remove(null);

        String filePath = "music";
        ObjectListing objectListing = txOssUpdateController.listObjects(filePath);
        List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();

        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
            System.out.println(cosObjectSummary);
            // 对象的 key
            String key = cosObjectSummary.getKey();
            // 对象的etag
            String etag = cosObjectSummary.getETag();
            // 对象的长度
            long fileSize = cosObjectSummary.getSize();
            // 对象的存储类型
            String storageClasses = cosObjectSummary.getStorageClass();

            Date lastModified = cosObjectSummary.getLastModified();
            String lastModifiedStr = formatter.format(lastModified);
            SuperMusic superMusic = new SuperMusic();
            if (key.contains(".")) {
                String musicName = key.substring(6, key.lastIndexOf("."));
                superMusic.setMusicName(musicName);
                superMusic.setMusicSize(fileSize);
                superMusic.setMusicKey(key);
                superMusic.setMusicUrl(baseUrl + "/" + key);
                superMusic.setLastModified(lastModifiedStr);
                //这里给音乐文件夹下表中添加数据
                superMusicService.save(superMusic);
            }

        }

        return R.ok().data("cosObjectSummaries", cosObjectSummaries);
    }


}




